package ctp.md;

import ctp.thostapi.*;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

import static ctp.thostapi.thosttraderapiConstants.*;


/**
 * 自定义MdApi类，实现登陆、行情订阅等功能
 */
public class MyMdApi {

    private static final Properties properties = new Properties();
    private static FileReader fr;


    static {

        try {
            fr = new FileReader("./config/config.ini");
        } catch (FileNotFoundException fileNotFoundException) {
            fileNotFoundException.printStackTrace();
        }
        try {
            properties.load(fr);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        try {
            fr.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    private String m_TFrontAddr = properties.getProperty("mdfront");
    private String m_BrokerId = properties.getProperty("brokerid");
    private String m_UserId = properties.getProperty("userid");
    private String m_PassWord = properties.getProperty("password");
    private String m_InstrumentID = properties.getProperty("mdid");


    private CThostFtdcMdApi mdApi;


    /**
     * 初始化函数
     */
    public void start() {
        mdApi = CThostFtdcMdApi.CreateFtdcMdApi();
        // System.out.println(mdApi.GetApiVersion());
        MyMdSpi mdSpi = new MyMdSpi(this);
        mdApi.RegisterFront(m_TFrontAddr);
        mdApi.RegisterSpi(mdSpi);
        mdApi.Init();
    }

    /**
     * 客户端等待一个接口实例线程的结束。
     */
    public void join() {
        mdApi.Join();
    }

    /**
     * 登陆函数
     */
    public void ReqUserLogin() {
        CThostFtdcReqUserLoginField field = new CThostFtdcReqUserLoginField();
        field.setBrokerID(m_BrokerId);
        field.setUserID(m_UserId);
        field.setPassword(m_PassWord);
        mdApi.ReqUserLogin(field, 0);
        System.out.println("Send login ok");

    }

    /**
     * 订阅行情函数
     */
    public void SubscribeMarketData() {
        System.out.println("start subscribe marketdata ...");
        mdApi.SubscribeMarketData(m_InstrumentID.split(","), m_InstrumentID.split(",").length);

    }

}
